<?php

namespace App\Http\Controllers\Api;

use App\Models\Type;
use Illuminate\Http\Request;
use App\Transformers\TypeTransformer;
use App\Http\Requests\Api\TypeRequest;

class TypesController extends Controller
{
    public function search(Request $request, Type $type)
    {
        $per_page = $request->input('per_page', 20);
        $query = $type->query();

        $query->where('delflag', false);

        if ($name = $request->name) {
            $query=$query->where('name', 'like', "%{$request->name}%");
        }

        if ($orderBy = $request->orderBy) {
            $query=$query->ordered();
        } else {
            $query=$query->recent();
        }

        $types = $query->paginate($per_page);

        return $this->response->paginator($types, new TypeTransformer());
    }

    public function index(Request $request, Type $type)
    {
        $per_page = $request->input('per_page', 20);
        $query = $type->query();

        $query->where('delflag', false);

        if ($orderBy = $request->orderBy) {
            $query=$query->ordered();
        } else {
            $query=$query->recent();
        }

        $types = $query->paginate($per_page);

        return $this->response->paginator($types, new TypeTransformer());
    }

    public function show(Type $type)
    {
        return $this->response->item($type, new TypeTransformer());
    }

    public function store(TypeRequest $request, Type $type)
    {

        $this->authorize('update', $type);

        $type->fill($request->all());
        $type->save();

        return $this->response->item($type, new TypeTransformer())
            ->setStatusCode(201);
    }

    public function update(TypeRequest $request, Type $type)
    {
        $this->authorize('update', $type);

        $type->update($request->all());

        return $this->response->item($type, new TypeTransformer());
    }

    public function destroy(Type $type)
    {
        $this->authorize('destroy', $type);

        $type->delflag=true;
        $type->save();

        return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag'=>true,
            ],
            'message'=>'删除成功',
        ])->setStatusCode(200);
    }
}